import { fetchToken, fetchTokenYellow } from "@/services/auth";
import { useCallback } from "react";
import { history, useModel } from "umi";

export default () => {
  const { setUserToken, userToken, isGetToken, getUserInfo } = useModel("user");
  const { EnvMode } = useModel("env");
  const getToken: Function = useCallback(
    (data: string) => {
      if (userToken.access_token || isGetToken) return;
      if (EnvMode === "YELLOW") {
        fetchTokenYellow(data).then((res) => {
          if (!res || !res.access_token) return;
          setUserToken({
            access_token: res.access_token,
            refresh_token: res.refresh_token,
          });
          getUserInfo(res.refresh_token);
          history.push("/editor/kpi");
        });
      } else {
        fetchToken(data).then((res) => {
          if (!res || !res.access_token) return;
          setUserToken({
            access_token: res.access_token,
            refresh_token: res.refresh_token,
          });
          getUserInfo(res.refresh_token);
          history.push("/editor/kpi");
        });
      }
    },
    [isGetToken, userToken]
  );

  return {
    getToken,
  };
};
